package utils;

import android.app.Activity;

import java.util.Stack;

/**
 * Created by YL on 2016/9/29.
 */

public class ActivityManagerUtils {
    private static Stack<Activity> activityStack = null;
    private static ActivityManagerUtils instance = null;

    private ActivityManagerUtils() {
    }

    public static ActivityManagerUtils getInstance() {
        if (instance == null) {
            instance = new ActivityManagerUtils();
        }
        return instance;
    }

    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }

    /**
     * 获取最后一个入栈的
     */
    public Activity currentActivity() {
        if (activityStack != null)
            return activityStack.lastElement();
        return null;
    }

    /**
     * 结束当前Activity
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    public void finishActivity_class(Class cls) {
        while (true) {
            Activity activity = activityStack.lastElement();
            if (activity == null) {
                break;
            }
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
                return;
            }
        }
    }

    public void finishAll(Class a) {
        if (activityStack != null) {
            for (Activity activity : activityStack) {
                if (!activity.getClass().equals(a)) {
                    activity.finish();
                    activity = null;
                }
            }
        }
    }

    /**
     * 结束所有的Activity
     */
    public void finishAll() {
        if (activityStack != null) {
            for (Activity activity : activityStack) {
                activity.finish();
                activity = null;
            }
        }
    }

    public void finishAcitivty_class_pro(Class cls) {
        if (activityStack == null)
            return;
        for (Activity activity : activityStack) {
            if (activity == null) {
                break;
            }
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
                return;
            }
        }
    }

}
